package com.lihaozhe.userservice.controller;

import com.lihaozhe.userservice.dto.UserDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 用户服务控制器
 * 提供用户相关的REST API
 * 这个服务会注册到Eureka，供其他服务调用
 *
 * @author 李昊哲
 * @version 1.0.0
 */
@RestController
@RequestMapping("/api/users")
public class UserController {
  // 模拟用户数据
  private final List<UserDTO> users = new ArrayList<>();
  private final Logger logger = LoggerFactory.getLogger(UserController.class);

  /**
   * 构造函数，初始化模拟数据
   */
  public UserController() {
    // 初始化一些测试用户
    users.add(new UserDTO(1L, "张三", "zhangsan@lihaozhe.com", "13800138001", "北京市朝阳区"));
    users.add(new UserDTO(2L, "李四", "lisi@lihaozhe.com", "13800138002", "上海市浦东新区"));
    users.add(new UserDTO(3L, "王五", "wangwu@lihaozhe.com", "13800138003", "广州市天河区"));
  }

  /**
   * 根据用户ID获取用户信息
   * GET /api/users/{id}
   */
  @GetMapping("/{id}")
  public UserDTO getUserById(@PathVariable("id") Long id) {
    logger.info("查询用户ID: {}", id);

    // 查找用户
    Optional<UserDTO> user = users.stream()
        .filter(u -> u.getId().equals(id))
        .findFirst();

    return user.orElse(null);
  }

  /**
   * 获取所有用户列表
   * GET /api/users
   */
  @GetMapping()
  public List<UserDTO> getAllUsers() {
    logger.info("获取所有用户列表");
    return users;
  }

  /**
   * 创建新用户
   * POST /api/users
   */
  @PostMapping()
  public UserDTO createUser(@RequestBody UserDTO user) {
    logger.info("创建用户: {}", user.getUsername());

    // 生成新用户ID
    Long newId = users.stream()
        .mapToLong(UserDTO::getId)
        .max()
        .orElse(0L) + 1;

    user.setId(newId);
    users.add(user);

    return user;
  }

  /**
   * 健康检查端点
   * GET /api/users/health
   */
  @GetMapping("/health")
  public Map<String, Object> health() {
    return Map.of(
        "status", "UP",
        "service", "user-service",
        "timestamp", System.currentTimeMillis()
    );
  }

  /**
   * 服务信息端点
   * GET /api/users/info
   */
  @GetMapping("/info")
  public Map<String, Object> info() {
    return Map.of(
        "name", "user-service",
        "description", "用户管理服务",
        "version", "1.0.0",
        "totalUsers", users.size()
    );
  }
}
